package edu.zut.servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(urlPatterns = "/demo3")
public class ServletDemo3 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        /**
         * 模拟一个统计站点访问次数的计数器
         * 计数器需要在不同web资源间（servlet）间共享
         * ServletContext：Servlet上下文，在web应用中仅此一个，所有资源共享
         */
        //获取一个ServletContext对象
        ServletContext servletContext = req.getServletContext();
        //获取计数器
        Object count = servletContext.getAttribute("count");
        if (count == null) {
            servletContext.setAttribute("count", 1);
        } else {
            int i = (Integer) count;
            i++;
            servletContext.setAttribute("count", i);
        }
        resp.getWriter().write("当前web站点访问次数是：" + servletContext.getAttribute("count"));
    }
}
